<?php
class Usertopay extends CS_Controller
{
    public function _init()
    {
        $this->load->helper('common');
        $this->load->library('alipay/alipaypc', null, 'alipaypc');
        //$this->load->library('chinapay/chinapay', null, 'chinapay');
        $this->load->library('ccbpay/ccbpay', null, 'ccbpay');
        $this->load->model('pay_failure_log_model', 'pay_failure_log');
        $this->load->model('pay_method_model', 'pay_method');
        $this->load->model('tourism_goods_attr_model','tourism_goods_attr');
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('account_log_model', 'account_log');
        $this->load->model('tourism_order_main_model', 'tourism_order_main');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('tourism_order_product_model', 'tourism_order_product');
    }

    /**
     * 下完订单后的跳转方法
     * 去付款的界面
     */
    public function payOrder($orderSn)
    {
        $this->data['payResult'] = $this->isExistOrder($orderSn);

        $this->load->view('tourism/usertopay/payment', $this->data);
    }

    /**
     * 网银去支付方法。
     */
    public function orderToPay()
    {
        $order_sn = $this->input->post('order_sn');//单订单
        $pay_bank = $this->input->post('pay_bank');
        // 获取要查看的订单
        $orderInfo = $this->isExistOrder($order_sn);

        switch ($pay_bank) {
            case '99' :  //余额支付
                $userAccount = $this->user_account->findByUid($this->uid);
                $this->data['userAccount'] = $userAccount->row();
                $this->data['orderInfo'] = $orderInfo;
                $this->load->view('tourism/usertopay/balancePay', $this->data);
                break;
            case '201':    //微信支付
                $url = $this->config->wap_base_url."tourismuser_wx_call.php?order_id=".$order_sn;
                header("Location:$url");
                break;
            case '200' : //银联支付
                $BgRetUrl = site_url('tourism/paycallback/chinapayNotifyU');//异步
                $PageRetUrl = site_url('tourism/payment/chinapayReturnU'); //同步
                $objPay = $this->chinapay->callChinapayApi($order_sn, bcadd($orderInfo->order_pay_total, $orderInfo->transport_cost, 2), 'notcart', $BgRetUrl, $PageRetUrl);
                break;
            case '1':      //支付宝支付
                $alipayParameter = $this->alipayParameter($pay_bank, $orderInfo);
                $this->alipaypc->callAlipayApi($alipayParameter);
                break;
            case '210' :    //建行支付
                $parameter = array(
                    'orderId' => $order_sn,
                    'payment' => bcadd($orderInfo->order_pay_total, $orderInfo->transport_cost, 2), //金额
                    'regInfo' => '', // 网站客户注册信息，中文需使用escape编码
                    'proInfo' => '', // 顾客购买的产品的信息，中文需使用escape编码
                    'remark1' => 'TOURISMU' , //备注1 商品
                    'remark2' => ''
                );
                $this->ccbpay->callCcbPay($parameter);
            default :  //支付出现问题
//                $this->load->view('payment/balancePay');
                break;
        }
    }
    
    /**
     * 获取支付宝需要参数。
     * @param paybank $bank_id
     * @param object $orderInfo
     * @param object $orderProductInfo
     * @return array
     */
    private function alipayParameter($pay_bank, $orderInfo)
    {
        $parameter = array(
            'out_trade_no' => $orderInfo->order_sn,
            'subject'      => $orderInfo->order_sn,
            'total_fee'    => bcadd($orderInfo->order_pay_total, $orderInfo->transport_cost, 2),
            'body'         => $orderInfo->order_sn,
            'notify_url'   => site_url('tourism/paycallback/alipayNotifyU'),
            'call_back_url'=> site_url('tourism/usertopay/alipayReturn'),
            'show_url'     => site_url('tourism/tourism'),
            'pay_method'   => $pay_bank,
        );
        $payBankCode = $this->pay_method->findByBankId($pay_bank);
        $parameter['defaultbank'] = $payBankCode->bank_code;
        return $parameter;
    }
    
    /**
     * 支付宝支付回调函数。
     */
    public function alipayReturn()
    {
        $response = $this->alipaypc->responseAlipayReturn();
        $order_sn = $this->input->get('out_trade_no');
        //更新订单状态
        $getDate = $this->input->get();

        if ($response) { //$response付款成功；
            $result = $this->tourism_order->findByOrderSn($order_sn);
            if ($result->num_rows() <= 0) {
                $this->redirect('tourism/tourism/payFail');
            }
            $orderInfo = $result->row();
            
            if($orderInfo->order_state >= 2 || $orderInfo->order_status >= 3){
                $this->redirect('tourism/tourism/paySuccess');
            }
            if($orderInfo->order_state != 1 && $orderInfo->order_status != 2){
                $this->alertJumpPre('订单状态有误!');
            }
            $params['order_state'] = 2;
            $params['order_status'] = 3;
            $params['pay_time'] = date('Y-m-d H:i:s');
            $params['pay_bank'] = 1;
            $this->tourism_order->updateStatus($order_sn, $params);
            if( !empty($orderInfo->pay_swim) ){  //更新U币
                $this->user_account->updateUserAccountUb($this->uid,$orderInfo->pay_swim);
            }
            //更新商品信息
            $product = $this->tourism_order->findTourismGoods($order_sn, true);
	        foreach ($product->result() as $item) {
	            $product_param['goods_attr_id'] = $item->goods_attr_id;
	            $product_param['number'] = $item->number;
	            $this->tourism_goods_attr->updateTourismSale($product_param);
	     
	        }
            //给供应商发短信，提醒供应商发货
            $tourismOrder = $this->tourism_order->findByOrderId($orderInfo->order_id);
            if (!empty($tourismOrder->cellphone)) {
                //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
                $this->sendCommonSmsInfo($tourismOrder->cellphone, 'SMS_136383536', ['providerName' => $tourismOrder->user_name]);
            }
            //更新商品信息结束
            $this->redirect('tourism/tourism/paySuccess');
        } else {
            $result = $this->pay_failure_log->findByOrderSn($order_sn);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($order_sn, $getDate, $response);
            }
            $this->redirect('tourism/tourism/payFail');
        }
    }

    public function wxCompletePay($order_sn)
    {
        $err_msg = $this->input->get('err_msg');
        if ($err_msg && $err_msg == 'get_brand_wcpay_request:ok') {
            $this->redirect('tourism/tourism/paySuccess');
        } else {
            $this->redirect('tourism/tourism/payFail');
        }
    }

    public function isExistOrder($order_sn)
    {
        $result = $this->tourism_order->findByOrderSn($order_sn);
        if ($result->num_rows() <= 0) {
            $this->alertJumpPre('订单信息不对');
        }
        return $result->row();
    }

    /**
     * 余额支付过程
     */
    public function balancePayForm()
    {
        $uid = $this->uid;
        $password = $this->input->post('password');
        $order_sn = $this->input->post('order_sn');

        $this->db->trans_start();
        $resultUser = $this->user->validateAccountPassword($uid, $password);
        if ($resultUser->num_rows() <= 0) {
            $this->alertJumpPre('支付密码填写错误!');
        }
        $userAccount = $resultUser->row();

        //订单是否支付
        $orderInfo = $this->isExistOrder($order_sn);
        if (!$orderInfo) {
            $this->alertJumpPre('订单信息不对');
        }
        if ($orderInfo->order_state >= 2 || $orderInfo->order_status >= 3) {
            $this->redirect('tourism/tourism/paySuccess');
        }
        if ($orderInfo->order_state != 1 && $orderInfo->order_status != 2) {
            $this->alertJumpPre('订单状态有误!');
        }

        //验证账户余额是否大于当前订单金额。
        $payTotal = bcadd($orderInfo->order_pay_total, $orderInfo->transport_cost, 2);
        if ($userAccount->amount_carry < $payTotal) {
            $this->alertJumpPre('当前余额不足支付订单。');
        }
        $params['order_state'] = 2;
        $params['order_status'] = 3;
        $params['pay_time'] = date('Y-m-d H:i:s');
        $params['pay_bank'] = 99;

        $this->db->trans_begin();
        $status = $this->tourism_order->updateStatus($order_sn, $params);
        if( !empty($orderInfo->pay_swim) ){  //更新U币
            $this->user_account->updateUserAccountUb($uid,$orderInfo->pay_swim);
        }
        //更新商品信息
        $product = $this->tourism_order->findTourismGoods($order_sn, true);
        foreach ($product->result() as $t=>$item) {
            $product_param['goods_attr_id'] = $item->goods_attr_id;
            $product_param['number'] = $item->number;
            $this->tourism_goods_attr->updateTourismSale($product_param);
        }
        //更新商品信息结束

        $updateAmountCarry = $this->user_account->updateAmountCarry($uid, $payTotal);
        $account_log = $this->account_log->insertAccountLogUser($orderInfo->order_id, $uid, $payTotal, 0, PAY); //PAY表示支付


        //给供应商发短信，提醒供应商发货
        $tourismOrder = $this->tourism_order->findByOrderId($orderInfo->order_id);
        if (!empty($tourismOrder->cellphone)) {
            //$item->user_name . '，您有一笔新的订单需要发货，请尽快发货';
            $this->sendCommonSmsInfo($tourismOrder->cellphone, 'SMS_136383536', ['providerName' => $tourismOrder->user_name]);
        }
        if ($this->db->trans_status() === true && $status && $updateAmountCarry && $account_log) {
            $this->db->trans_complete();
            $this->redirect('tourism/tourism/paySuccess');
        } else {
            $this->db->trans_rollback();
            $this->redirect('tourism/tourism/payFail');
        }
    }
}
